package com.meshnetics.gb.type.impl;

/**
 * Utility class providing some static algorithms to convert to and from strings.
 *
 * @author AKovylin
 */
public class StringUtils {
    private StringUtils() {
    }

    public static String getSimpleName(Class clazz) {
        String s = clazz.getName();
        return s.substring(s.lastIndexOf('.') + 1);
    }

    public static String toHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            appendAsHex(sb, bytes[i]);
        }
        return sb.toString();
    }

    public static String toHexString(byte b) {
        StringBuffer sb = new StringBuffer(2);
        appendAsHex(sb, b);
        return sb.toString();
    }

    public static void appendAsHex(StringBuffer sb, byte b) {
        sb.append(Character.forDigit((b >>> 4) & 0x0f, 16));
        sb.append(Character.forDigit(b & 0x0f, 16));
    }

    public static byte recoverByteFromHexString(String s, int offset) {
        int res = 0;
        int digit = Character.digit(s.charAt(offset), 16);
        if (digit == -1) {
            throw new IllegalArgumentException("non-hex char at " + offset + " position of '" + s + '\'');
        }
        res += digit;
        res = res << 4;
        digit = Character.digit(s.charAt(offset + 1), 16);
        if (digit == -1) {
            throw new IllegalArgumentException("non-hex char at " + (offset + 1) + " position of '" + s + '\'');
        }
        res += digit;
        return (byte) (res & 0xff);
    }

    public static byte[] recoverBytesFromHexString(String s, int charOffset, int charLength) {
        if (charLength % 2 != 0) {
            throw new IllegalArgumentException("length must be divisible by 2");
        }
        byte[] res = new byte[charLength / 2];
        for (int i = 0; i < res.length; i++) {
            res[i] = recoverByteFromHexString(s, charOffset + i * 2);
        }
        return res;
    }
}
